<template>
  <div class="mengli-order-create">
    <CreateClient
      ref="clientInfoRef"
      :disabled-tax-amount="disabledTaxAmount"
    />
    <CreateOrder
      ref="orderInfoRef"
      :disabled-tax-amount="disabledTaxAmount"
      style="margin-top:12px;"
    />
    <CreateResource
      ref="resourceInfoRef"
      :no-display-props="['resourceType']"
      style="margin-top:12px;"
    />
    <CreatePublish
      ref="publishInfoRef"
      style="margin-top:12px;"
    />
    <DiscountInfo
      ref="discountInfoRef"
      :talent-options="detailInfo.talentOptions"
      :is-create="true"
    />
    <div class="select-related-container">
      <Title title="关联合同和发票" />
      <div style="margin-top: 32px;">
        <InvoiceAndContract ref="ContractSelect" :sub-title="'关联合同'" :type="1" placeholder="请输入合同编号/合同名称" />
      </div>
      <div style="margin-top: 32px;">
        <InvoiceAndContract ref="InvoiceSelect" :sub-title="'关联发票'" :type="2" target-keyword="no" placeholder="请输入发票编号/发票号码" />
      </div>
    </div>
    <div class="crm-add-btn">
      <el-button v-if="hasRouteAuth('crm:projectInfo:addOrder')" :loading="btnLoading" type="primary" size="small" class="submit-btn" @click="toSubmit">{{ isEdit ?'保存订单':'创建订单' }}</el-button>
      <el-button type="info" size="small" class="back-btn cancel-btn-style" @click="toBack">取消</el-button>
    </div>
  </div>
</template>
<script>
import CreateClient from './orderModule/createClient';
import CreateOrder from './orderModule/createOrder';
import CreateResource from '@/components/CreateOrder/createResource';
import CreatePublish from '@/components/CreateOrder/createPublish';
import DiscountInfo from './orderModule/discount';
import InvoiceAndContract from '@/components/CreateOrder/InvoiceAndContract';
import Title from '@/components/Title';
import ElMessage from '@/utils/message';
import { mengliOrderInfo, getOrderAdd, getOrderEdit } from '@/api/mengli';
import { hasRouteAuth } from '@/utils/permission';
export default {
  components: {
    CreateOrder,
    CreateResource,
    CreatePublish,
    DiscountInfo,
    CreateClient,
    InvoiceAndContract,
    Title
  },
  data() {
    return {
      id: null,
      btnLoading: false,
      orderType: null,
      detailInfo: {},
      disabledTaxAmount: false
    };
  },
  computed: {
    isEdit() {
      return this.id !== '';
    }
  },
  created() {
    this.id = Number(this.$route.params.id) || '';
    this.orderType = this.$route.query.type || '0';
    if (this.id) {
      this.getOrderDetail();
    }
  },
  methods: {
    hasRouteAuth,
    getOrderDetail() {
      mengliOrderInfo(this.id).then(({ data }) => {
        this.detailInfo = data;
        if (this.$refs.clientInfoRef) this.$refs.clientInfoRef.insertDetail(data);
        if (this.$refs.orderInfoRef) {
          this.$refs.orderInfoRef.insertDetail(data);
        }
        if (this.$refs.resourceInfoRef) this.$refs.resourceInfoRef.insertDetail(data);
        if (this.$refs.publishInfoRef) this.$refs.publishInfoRef.insertDetail(data);

        if (this.$refs.discountInfoRef) this.$refs.discountInfoRef.insertDetail(data);
        if (this.$refs.ContractSelect) this.$refs.ContractSelect.setDefault(data.contract);
        if (this.$refs.InvoiceSelect) this.$refs.InvoiceSelect.setDefault(data.invoiceInfo);
        // writeOffStatus 核销状态（0: '待核销', 1: '已完成', 2: '部分核销'）
        // 已完成和部分核销后不能编辑含税金额
        this.disabledTaxAmount = data.financeRecord.writeOffStatus === 1 || data.financeRecord.writeOffStatus === 2;
      }).catch(err => {
        console.log(err);
      });
    },
    toSubmit(isValidate = true) {
      const clientSubParams = this.$refs.clientInfoRef ? this.$refs.clientInfoRef.getParams() : {};
      const marketParams = this.$refs.orderInfoRef ? this.$refs.orderInfoRef.getParams().clientInfo : {};
      const clientParams = Object.assign(clientSubParams, marketParams);
      // 订单信息
      const orderInfoRefParams = this.$refs.orderInfoRef ? this.$refs.orderInfoRef.getParams().orderInfo : {};
      // ip形象
      const ipAry = this.$refs.orderInfoRef ? this.$refs.orderInfoRef.getParams().ipAry : [];
      // 资源信息
      const resourceInfoParams = this.$refs.resourceInfoRef ? this.$refs.resourceInfoRef.getParams() : {};
      // 发布信息
      const publishInfoParams = this.$refs.publishInfoRef ? this.$refs.publishInfoRef.getParams() : {};
      const orderParams = Object.assign(Object.assign(orderInfoRefParams, resourceInfoParams), publishInfoParams);

      const discountInfoParams = this.$refs.discountInfoRef ? this.$refs.discountInfoRef.getParams() : {};
      delete discountInfoParams.costConfirm;
      const params = {
        orderInfo: orderParams,
        costBreakdown: discountInfoParams,
        clientInfo: clientParams,
        ipAry
      };
      const validatePromise = [];
      if (this.$refs.clientInfoRef) validatePromise.push(this.$refs.clientInfoRef.validateForm(isValidate));
      if (this.$refs.orderInfoRef) validatePromise.push(this.$refs.orderInfoRef.validateForm(isValidate));
      if (this.$refs.discountInfoRef) validatePromise.push(this.$refs.discountInfoRef.validateForm(isValidate));
      if (this.$refs.resourceInfoRef) validatePromise.push(this.$refs.resourceInfoRef.validateForm(isValidate));
      const relatedIds = this.getRelatedIds();
      params.invoiceIds = relatedIds.invoiceIds;
      params.contractIds = relatedIds.contractIds;
      Promise.all(validatePromise).then(res => {
        let discountError = true;
        if (this.$refs.discountInfoRef && !params.saveDraft) {
          discountError = this.$refs.discountInfoRef.validateEmpty(params.costBreakdown);
        }
        if (!discountError) {
          return;
        }
        if (this.isEdit) {
          this.editOrder(params);
        } else {
          this.addOrder(params);
        }
      }).catch((err) => {
        console.error(err);
        ElMessage.warning('请检查信息是否填写完整');
      });
    },
    addOrder(params) {
      this.btnLoading = true;
      getOrderAdd(params).then(res => {
        if (res.code === 200) {
          ElMessage.success('创建成功');
          this.toBack();
        }
        this.btnLoading = false;
      }).catch(err => {
        console.error(err);
        this.btnLoading = false;
      });
    },
    editOrder(params) {
      this.btnLoading = true;
      getOrderEdit(this.id, params).then(res => {
        if (res.code === 200) {
          ElMessage.success('保存成功');
          this.toBack();
        }
        this.btnLoading = false;
      }).catch(err => {
        console.error(err);
        this.btnLoading = false;
      });
    },
    toBack() {
      const source = this.$route.query.source;
      const query = {};
      if (!source || source !== 'all') {
        query.type = 3;
      }
      this.$router.push({
        name: 'mengliOrder',
        query
      });
    },
    // 获取合同和发票
    getRelatedIds() {
      const contractSelect = this.$refs.ContractSelect;
      const invoiceSelect = this.$refs.InvoiceSelect;
      let contractIds = [];
      let invoiceIds = [];
      if (contractSelect && contractSelect.selectData) {
        contractIds = contractSelect.selectData.map(i => i.id);
      }
      if (invoiceSelect && invoiceSelect.selectData) {
        invoiceIds = invoiceSelect.selectData.map(i => i.id);
      }
      return {
        contractIds: contractIds.join(','),
        invoiceIds: invoiceIds.join(',')
      };
    }
  }
};
</script>

<style lang="scss" scoped>
.mengli-order-create {
  .select-related-container {
    background:rgba(255,255,255,1);
    box-shadow:2px 4px 13px 0px rgba(221,225,234,1);
    border-radius:12px;
    margin-top: 12px;
    padding: 24px;
  }
  & ::v-deep {
    .el-input__inner  {
      width: 240px;
      line-height: 16px;
    }
    .el-form-item {
      margin-bottom: 32px;
    }
    .el-date-editor.el-input {
      width: 240px;
    }
  }
}
</style>
